<!--
 * @Description: 点单页面
 * @Author: Kerwin
 * @Date: 2025-04-29 14:04:58
 * @LastEditTime: 2025-11-22 14:22:39
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view v-if="!isEmpty" class="orderShop">
    <!-- <Chome></Chome> -->
    <view class="top">
      <view class="searchBar">
        <u-search
          shape="round"
          @custom="debouncedSearch"
          @search="debouncedSearch"
          @clear="handleCancel"
          :clearabled="true"
          :show-action="true"
          :action-text="searchText"
          placeholder="请输入关键词"
          v-model="searchWord"
        ></u-search>
      </view>
      <view class="shopDetil" @click="mapDialog">
        <view class="left">
          <view style="font-weight: 700">
            <van-icon style="font-weight: 700" name="shop-o" />
            {{ shopInfo.name }}
          </view>
          <view style="margin: 10rpx 0; font-size: 20rpx"
            >距离 {{ shopInfo.distance }} | {{ shopInfo.addr }}
          </view>
        </view>
        <view class="right">
          <image class="content-image" :src="adress" alt="" />
        </view>
      </view>
    </view>
    <!-- 预加载状态 -->
    <view v-if="isloading">
      <view v-if="goodesList.length > 0">
        <!-- 搜索 -->
        <view v-if="searchGoods.length > 0" class="searchList">
          <view
            class="card"
            @click="gotoDetile(item)"
            v-for="item in searchGoods"
            :key="item.shopProductId"
          >
            <!-- 图片 -->
            <van-image
              width="160rpx"
              height="160rpx"
              fit="cover"
              :src="item.image"
            />
            <!-- 详情 -->
            <view class="detail">
              <view
                style="
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                "
              >
                {{ item.name }}
              </view>
              <view style="margin: 10rpx 0" v-if="item.userScoreMoney != 0">
                <u-tag :text="`立省${item.userScoreMoney}元`" type="warning" />
              </view>
              <view class="flexCenter">
                <text
                  style="
                    color: #df3b3f;
                    font-size: 30rpx;
                    font-weight: 700;
                    margin-right: 10rpx;
                  "
                  >￥{{
                    shopData.shopMode == 6 ? item.money : item.userMoney
                  }}</text
                >
                <view class="flexCenter" v-if="item.userScoreMoney != 0">
                  <text
                    style="
                      color: #ff5a5d;
                      font-size: 24rpx;
                      font-weight: 700;
                      margin-right: 10rpx;
                    "
                    ><text>{{ shopData.shopMode == 6 ? '-' : '+ ' }}</text
                    >{{ item.userScoreMoney }}</text
                  >
                  <text>
                    <u-image
                      width="35rpx"
                      height="30rpx"
                      :src="quan1"
                      mode="scaleToFill"
                  /></text>
                </view>
              </view>
              <view
                v-if="item.money != item.userMoney"
                style="
                  color: #b4b4b4;
                  font-size: 24rpx;
                  text-decoration: line-through;
                "
                >￥{{ item.money }}</view
              >
            </view>
            <!-- 规格 -->
            <view>
              <van-badge
                v-if="getNumById(item.hwProductId) != 0"
                :content="getNumById(item.hwProductId)"
                max="99"
              >
                <van-button color="#ff6c18" type="warning" size="mini"
                  >选规格</van-button
                >
              </van-badge>
              <van-button v-else color="#ff6c18" type="warning" size="mini"
                >选规格</van-button
              >
            </view>
          </view>
        </view>
        <!-- 无搜索 -->
        <view class="bottom" v-else>
          <van-tree-select
            :style="{
              height:
                chooseGoods.length > 0
                  ? 'calc(100vh - 500rpx)'
                  : 'calc(100vh - 300rpx)'
            }"
            v-model:active-id="activeIds"
            v-model:main-active-index="activeIndex"
            :items="goodesList"
          >
            <template #content>
              <view v-if="goodesList[activeIndex]">
                <view
                  class="goodsItem"
                  @click="gotoDetile(item)"
                  v-for="item in goodesList[activeIndex].children"
                  :key="item.id"
                >
                  <!-- 图片 -->
                  <van-image
                    width="160rpx"
                    height="160rpx"
                    fit="cover"
                    :src="item.image"
                    style="margin-right: 20rpx"
                  />
                  <!-- 详情 -->
                  <view class="detail" style="width: 47%">
                    <view
                      style="
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                      "
                    >
                      {{ item.name }}
                    </view>
                    <view
                      v-if="item.userScoreMoney != 0"
                      style="margin: 10rpx 0"
                    >
                      <u-tag
                        :text="`立省${item.userScoreMoney}元`"
                        type="warning"
                      />
                    </view>
                    <view class="flexCenter">
                      <text
                        style="
                          color: #df3b3f;
                          font-size: 30rpx;
                          font-weight: 700;
                          margin-right: 10rpx;
                        "
                        >￥{{
                          shopData.shopMode == 6 ? item.money : item.userMoney
                        }}</text
                      >
                      <view class="flexCenter" v-if="item.userScoreMoney != 0">
                        <text
                          style="
                            color: #ff5a5d;
                            font-size: 24rpx;
                            font-weight: 700;
                            margin-right: 10rpx;
                          "
                          ><text>{{ shopData.shopMode == 6 ? '-' : '+ ' }}</text
                          >{{ item.userScoreMoney }}</text
                        >
                        <text>
                          <u-image
                            width="35rpx"
                            height="30rpx"
                            :src="quan1"
                            mode="scaleToFill"
                        /></text>
                      </view>
                    </view>
                    <view
                      v-if="item.money != item.userMoney"
                      style="
                        color: #b4b4b4;
                        font-size: 24rpx;
                        text-decoration: line-through;
                      "
                      >￥{{ item.money }}</view
                    >
                  </view>
                  <!-- 规格 -->
                  <view>
                    <van-badge
                      v-if="getNumById(item.hwProductId) != 0"
                      :content="getNumById(item.hwProductId)"
                      max="99"
                    >
                      <van-button color="#ff6c18" type="warning" size="mini"
                        >选规格</van-button
                      >
                    </van-badge>
                    <van-button
                      v-else
                      color="#ff6c18"
                      type="warning"
                      size="mini"
                      >选规格</van-button
                    >
                  </view>
                </view>
              </view>
            </template>
          </van-tree-select>
        </view>
      </view>
      <view v-else style="margin-top: 200rpx">
        <u-empty text="没有更多商品，请重新选择餐厅" mode="list"></u-empty>
      </view>
    </view>

    <u-loadmore v-else status="loading" />
    <!-- 底部结算 -->
    <CartFooter :shopData="shopInfo" v-if="chooseGoods.length > 0"></CartFooter>
    <!-- 地图弹出框 -->
    <van-popup
      v-model:show="showMap"
      round
      position="bottom"
      :style="{ height: '30%' }"
    >
      <view class="map">
        <van-button class="btn" @click="openGMap" type="default"
          >高德地图</van-button
        >
        <van-button class="btn" @click="openBMap" type="default"
          >百度地图</van-button
        >
        <van-button class="btn" @click="openTMap" type="default"
          >腾讯地图</van-button
        >
        <van-button class="btn" @click="copyMap" type="default"
          >复制地址</van-button
        >
        <van-button class="btn btn2" type="default" @click="showMap = false"
          >取消</van-button
        >
      </view>
    </van-popup>
  </view>

  <!-- 空状态 -->
  <u-empty v-else :src="kf" :text="text" mode="list">
    <template #bottom v-if="!isApp">
      <van-button
        style="margin-top: 20rpx"
        round
        @click="retry"
        type="primary"
        class="bottom-button"
        >返回</van-button
      >
    </template>
  </u-empty>
</template>

<script setup lang="ts">
import {
  onReady,
  onShow,
  onLoad,
  onReachBottom,
  onPageScroll,
  onShareAppMessage,
  onPullDownRefresh
} from '@dcloudio/uni-app'
import { computed, reactive, ref, watch } from 'vue'
import { route } from '@/utils/common'
import { storeToRefs } from 'pinia'
// #region ***************** api *************************/
import { productApi, orderApi } from '@/api'
// #region ***************** 图片 *************************/
import adress from '@/static/xfl/adress.svg'
import shopIcn from '@/static/xfl/shopIcn2.png'
import itemImg from '@/static/xfl/item.png'
import quan1 from '@/static/xfl/quan1.png'
import kf from '@/static/xfl/kf2.png'
// #region ***************** 组件 *************************/
import CartFooter from './c_cartFooter.vue'
import Chome from './c_home.vue'
// #region ***************** 工具 *************************/
import { useShopInfoStore, useCartStore } from '@/store'
import debounce from 'lodash/debounce'
//  #endregion

// #region ***************** 初始数据 *************************/
const carStore = useCartStore()
const shopStore = useShopInfoStore()
const shopData = ref()
const carShopData = ref()
const shopInfo = ref({
  name: '',
  addr: '',
  distance: '',
  shopId: '',
  address: '',
  brandId: ''
})
const goodesList = ref<any>([])
const searchWord = ref('') //搜索
const searchText = ref('搜索') //搜索
const activeIds = ref([1, 2]) //多选id
const activeIndex = ref(1) //当前选中
// const chooseGoods = ref<any>([])
const searchGoods = ref<any>([])
const showBottom = ref(false) //当前选中
const isEmpty = ref(false) //接口报错
const isloading = ref(false) //预加载
const goodsNum = ref(1)
const orderData = ref<any>({})
const isApp = ref(false)
const chooseGoods = computed(() => carStore.goodsList)
const showMap = ref(false) //地图展示
const locationObj = ref<any>({})
const locationEndObj = ref<any>({})
const brandId = computed(() => shopStore.brandId)
const text = ref('该平台入驻店铺暂时无法下单,请稍后再试...')
const shopTypeAllList = ref([
  { name: '黑银', id: 0 },
  { name: '花积分', id: 1 },
  { name: '链动模式', id: 2 },
  { name: '酒慕网', id: 3 },
  { name: '鑫复来', id: 4 },
  { name: '长来科技', id: 6 }
])
const disabled = ref(false)
// #engregion

//#region ***************** 购物 *************************/

//选择规格
const gotoDetile = (item: any) => {
  if (disabled.value)
    return uni.showToast({ title: '请重新进入,当前模式有误', icon: 'error' })
  uni.navigateTo({
    url: `/pages/bigLife/orderDetile?shopMode=${shopData.value.shopMode}&restaurantId=${shopData.value.shopId}&hwProductId=${item.hwProductId}&shopBrandId=${shopData.value.brandId}&shopProductSkuId=${item.shopProductId}`
  })
  // carStore.setGoodsItem(item)
}

//#endregion
// #region ***************** 弹窗 *************************/
//打开弹窗
const dialog = () => {
  showBottom.value = true
}

//清空购物车
const clearChooseGoods = () => {
  carStore.clearGoods() // 直接调用 store 方法清空
  showBottom.value = false
}
//增减数量
const updateCartItemQuantity = (item: any) => {
  if (item.num === 0) {
    carStore.reduceGoods(item)
  }
  if (chooseGoods.value.length === 0) {
    showBottom.value = false
  }
}

//地图弹窗
const mapDialog = () => {
  showMap.value = true
}

//#endregion

// #region ***************** 获取商品信息 *************************/
//获取商品列表
const getShopProductList = async () => {
  isloading.value = false
  try {
    // debugger
    const { data } = await productApi.getlistByBrandId({
      shopMode: shopData.value.shopMode,
      shopBrandId: shopData.value.brandId,
      restaurantId: shopData.value.shopId
    })
    // 确保 data 和 data.categoryList 存在
    if (data && data.categoryList && data.categoryList.length > 0) {
      goodesList.value = data.categoryList.map((item: any) => {
        return {
          text: item.categoryName,
          children: item.shopProducts || [] // 避免子项为 undefined
        }
      })
      locationEndObj.value = {
        latEnd: data.shopRestaurant.latitude,
        lotEnd: data.shopRestaurant.longitude
      }
      shopInfo.value.shopId = shopData.value.shopId
      shopInfo.value.name = data.shopRestaurant.name
      shopInfo.value.addr =
        data.shopRestaurant.provinceName +
        data.shopRestaurant.cityName +
        data.shopRestaurant.address
      shopInfo.value.address = shopInfo.value.addr
      shopInfo.value.brandId = data.shopRestaurant.shopBrandId
      // carShopData.value = {address: shopInfo.value.addr, brandId }

      shopStore.setShopInfo(shopInfo.value)
    } else {
      goodesList.value = [] // 默认空结构
    }
    isEmpty.value = false
  } catch (error: any) {
    console.log('接口报错', error)

    const errorText = error?.msg?.includes('餐厅未营业')
    isEmpty.value = true
    if (errorText) {
      text.value = '当前餐厅未营业，请更换店铺'
    } else {
      text.value = '该平台入驻店铺暂时无法下单,请稍后再试...' // 或者其他默认提示
    }
  } finally {
    isloading.value = true
  }
}

// 获取商品规格数量
const getNumById = (id: number) => {
  return chooseGoods.value
    .filter((good: any) => good.productId === id)
    .reduce((sum: number, good: any) => sum + (good.num || 0), 0)
}
//商品总金额
const totalMoney = computed(() => {
  return chooseGoods.value.reduce(
    (sum: any, item: any) => sum + item.productPrice * item.num,
    0
  )
})

//商品总数量
const allNum = computed(() => {
  return chooseGoods.value.reduce((sum: any, item: any) => sum + item.num, 0)
})

// 格式化金额为两位小数
function formatPrice(value: number): string {
  return value.toFixed(2)
}

// 格式化金额为两位小数（不四舍五入）
function slicePrice(value: number, truncate = true): string {
  let num: number

  if (truncate) {
    const factor = 100
    num = Math.floor(value * factor) / factor // 截断逻辑
  } else {
    num = value // 或者保留原值
  }

  return num.toFixed(2) // 转成字符串格式 "xx.xx"
}

// #endregion

// #region ***************** 搜索 *************************/
watch(
  () => searchGoods.value,
  (newValue, oldValue) => {
    if (newValue.length == 0) {
      searchText.value = '搜索'
    } else {
      searchText.value = '取消'
    }
  }
)

//点击搜索
const handleSearch = async () => {
  if (searchText.value === '取消') {
    searchWord.value = ''
    searchGoods.value = []
    searchText.value = '搜索'
    return
  }

  const { data } = await productApi.getlistByBrandId({
    shopMode: shopData.value.shopMode,
    shopBrandId: shopData.value.brandId,
    restaurantId: shopData.value.shopId,
    keyword: searchWord.value
  })

  if (data?.shopProducts?.length > 0) {
    searchGoods.value = data.shopProducts
  } else {
    uni.showToast({ title: '暂无此商品', icon: 'none' })
  }
}

// 👇 防抖处理搜索事件
const debouncedSearch = debounce(() => {
  handleSearch()
}, 300)

watch(
  () => searchGoods.value,
  (newVal) => {
    searchText.value = newVal.length > 0 ? '取消' : '搜索'
  }
)

// 取消搜索
const handleCancel = () => {
  searchWord.value = ''
  searchGoods.value = []
}
// #endregion

// #region ***************** 地图唤起 *************************/
//高德
const openGMap = () => {
  const { latitude, longitude } = locationObj.value
  const { latEnd, lotEnd } = locationEndObj.value
  window.location.href = `https://uri.amap.com/marker?position=${lotEnd},${latEnd}&name=${shopInfo.value.name}&coordinate=gaode&callnative=0`
}
//百度
const openBMap = () => {
  const { latitude, longitude } = locationObj.value
  const { latEnd, lotEnd } = locationEndObj.value
  console.log(latitude, longitude, latEnd, lotEnd)
  window.location.href = `https://api.map.baidu.com/marker?location=${latEnd},${lotEnd}&title=${shopInfo.value.name}&output=html`
}

//腾讯
const openTMap = () => {
  const { latitude, longitude } = locationObj.value
  const { latEnd, lotEnd } = locationEndObj.value
  window.location.href = `https://apis.map.qq.com/uri/v1/marker?marker=coord:${latEnd},${lotEnd};title=${shopInfo.value.name}`
}

const copyMap = () => {
  const address = shopInfo.value?.addr || '地址信息不可用' // 获取地址信息，若无则显示默认文本

  uni.setClipboardData({
    data: address,
    success: () => {
      showMap.value = false
      uni.showToast({
        title: '复制成功'
      })
    },
    fail: () => {
      showMap.value = false
      uni.showToast({
        title: '复制失败',
        icon: 'none'
      })
    }
  })
}

function retry() {
  uni.navigateBack() // 返回上一页重试
}

// #region ***************** 页面周期 *************************/

// onShow(() => {
//   shopInfo.value = goodStore.shopInfo

// })

onLoad((option: any) => {
  console.log('option', option)

  shopData.value = option
  if(option.mode){
    shopData.value.shopMode = option.mode
  }
  // 如果需要保存距离信息，可以单独处理
  if (option.distance) {
    shopInfo.value.distance = option.distance
    shopInfo.value.addr = option.address
    shopInfo.value.name = option.name
  }
  if (option?.from && option.from.toLowerCase() === 'app') {
    isApp.value = true
    shopStore.setIsApp(isApp.value)

    // 判断是否是从附近商店进入
    if (option.nearby == 1) {
      clearChooseGoods() // 直接调用 store 方法清空
    }

    // #ifdef H5
    // @ts-ignore
    window.JSBridge.registerEvent('HYUserEvent', async (data) => {
      console.log('收到 App 用户信息:', data)
      getShopProductList()
    })
    // #endif
  } else {
    // 修正这里：不要直接把字符串赋值给 shopInfo
    getShopProductList()
    locationObj.value = uni.getStorageSync('wzLocation') // 当前自己的定位

    shopStore.setBrandId(option.brandId)
  }
  // 安全地处理 mode 参数
  if (option?.shopMode) {
    try {
      const modeArr = shopTypeAllList.value.filter(
        (item) => item.id == option.mode
      )
      // 确保存储的是有效的 JSON 字符串
      uni.setStorageSync('hyType', JSON.stringify(modeArr[0]))
      uni.setStorageSync('shopMode', option?.shopMode)
    } catch (e) {
      console.error('序列化 hyType 失败:', e)
    }
  } else {
    disabled.value = true
    uni.showToast({ title: '请重新进入,当前模式有误', icon: 'error' })
  }
})
// #endregion
</script>

<style lang="scss" scoped>
.orderShop {
  height: 100vh;

  .top {
    padding: 40rpx;
    padding-bottom: 25rpx;
    box-shadow: 0rpx 5rpx 18rpx 8rpx rgba(0, 0, 0, 0.07);
    background-color: rgba(255, 255, 255, 1);

    .shopDetil {
      margin-top: 20rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .content-image {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }

  .searchList {
    margin-top: 20rpx;
    padding: 20rpx;

    .card {
      margin-top: 40rpx;
      padding: 20rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-radius: 40rpx;
      background-color: #fff;

      .detail {
        width: 50%;
      }
    }
  }

  .bottom {
    margin-top: 30rpx;
    width: 100%;

    /* 或固定宽度 */
    .goodsItem {
      display: flex;
      align-items: center;
      padding: 20rpx;
      justify-content: space-between;

      .detail {
        width: 50%;
      }
    }
  }

  // .footer {
  //     position: fixed;
  //     bottom: 0;
  //     width: 100%;
  //     height: 180rpx;
  //     background-color: #fff;
  //     box-shadow: 0rpx -8rpx 16rpx 0rpx rgba(0, 0, 0, 0.07);

  // }
  .diaolog {
    position: fixed;
    bottom: 100rpx;
    // height: 300rpx;
    width: 100%;
    background-color: #fff;

    .bootomDiaolog {
      height: 340rpx;
      margin-bottom: 70rpx;
      // overflow: hidden;
      // overflow-y: auto;

      .chooseGoods {
        padding: 20rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-top: 2rpx solid #efeef2;

        .left {
          display: flex;
          justify-content: start;
          width: 70%;

          .img {
            // width: 100rpx;
            margin-right: 40rpx;
          }

          .words {
            width: calc(100% - 200rpx);

            .goodName {
              //    flex: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0rpx;
    width: 100%;
    // height: 130rpx;
    padding: 20rpx 0;
    background-color: #fff;
    box-shadow: 16rpx -38rpx 100rpx 0rpx rgba(0, 0, 0, 0.07);

    .custom-price {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 100rpx;
      width: 100%;
      // align-items: baseline; // 使用 baseline 对齐，使整数和小数部分垂直对齐
      font-size: 24rpx;
      // margin-bottom: 50rpx;
      // margin: 0 50rpx;
      // margin-left: 100rpx;

      .price-integer {
        color: #e64340;
        font-weight: bold;
        font-size: 36rpx; // 整数部分字体更大
        margin-right: 8rpx; // 调整间距，使 . 和小数部分紧贴
      }

      .price-decimal {
        color: #e64340;
        font-size: 24rpx; // 小数部分字体正常大小
        margin-left: -8rpx; // 调整间距，使 . 和小数部分紧贴
      }

      .original-price {
        color: #999;
        text-decoration: line-through;
        margin: 0 10rpx; // 原价与现价之间的间距
      }
    }

    .textMonry {
      margin-right: 30rpx;
      font-size: 24rpx;
      color: #e0a66c;
    }
  }
}

.flexCenter {
  display: flex;
  align-items: center;
}

.map {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f7f8fa;

  .btn {
    width: 100%;
    height: 80rpx;
    border: none;
    background-color: #fff;
  }

  .btn2 {
    margin-top: 20rpx;
  }
}

:deep(.van-stepper--round .van-stepper__plus) {
  background-color: #ff6c18;
}

:deep(.van-stepper--round .van-stepper__minus) {
  color: #ff6c18;
  border: 2rpx solid #ff6c18;
}

:deep(.van-submit-bar__bar) {
  justify-content: space-between;
  // flex-wrap: wrap;
  margin: 10rpx 0;
  // padding: 40rpx 0;
}

:deep(.van-tree-select__content) {
  flex: 3;
}

:deep(.u-icon--bottom .u-icon__img) {
  width: 500rpx !important;
  height: 400rpx !important;
}

:deep(.u-icon__label) {
  font-size: 28rpx !important;
}
</style>
